<template>
  <div>
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="权限字符">
            <el-input v-model="form.roleKey" style="width: 250px" clearable />
          </el-form-item>
          <el-form-item label="角色状态">
            <el-select v-model="value" placeholder="请选择" style="width: 250px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="createTime"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleSelectTime"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn-search"
              round
              icon="el-icon-search"
              size="medium"
              @click="initTable"
              >搜索</el-button
            >
            <el-button
              class="btn-search"
              round
              icon="el-icon-refresh"
              size="medium"
              @click="resetForm('form')"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </card-search>
    </el-collapse-transition>

    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:role:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:role:edit')"
            class="btn-search"
            size="small"
            icon="el-icon-edit"
            :disabled="btnDisabledSingle"
            @click="handleClick(null, 'edit')"
            >编辑</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:role:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:role:export')"
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            @click="handleClick(null, 'export')"
            >导出</el-button
          >
          <el-input
            v-if="isSuperAdmin || hasPermission('system:role:list')"
            v-model="input"
            placeholder="请输入角色名称"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
            @change="initTable"
          >
            <el-button slot="append" icon="el-icon-search" @click="initTable"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :search-show="hasPermission('system:role:list') || isSuperAdmin"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        stripe
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :sortable="item.sortble"
          :show-overflow-tooltip="true"
          :align="item.align"
        >
          <template #default="scope">
            <span v-if="item.prop === 'status'">{{
              scope.row[item.prop] == "0" ? "正常" : "停用"
            }}</span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          align="center"
          v-if="isSuperAdmin || hasPermission('system:role:dataManage')"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleClick(scope.row, 'assign')"
              ><svg-icon
                icon-class="lockfff"
                class-name="card-panel-icon"
              />分配用户</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <dialog-role
      v-model="dialogRoleVisible"
      :field="field"
      :rowData="rowData"
      @refresh="initTable"
      @close="
        () => {
          dialogRoleVisible = false;
        }
      "
    />
    <AssignUser
      v-model="dialogAssignVisible"
      :field="field"
      :rowData="rowData"
      @close="
        () => {
          dialogAssignVisible = false;
        }
      "
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogRole from "./component/AddRole.vue";
import AssignUser from "./component/AssignUser.vue";
import XyPagination from "@/components/XyPagination";
import { roleList, roleRemove, roleExport } from "@/api/systemmanagement";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
export default {
  name: "BusinessList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    DialogRole,
    AssignUser,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      dialogRoleVisible: false,
      field: "",
      form: {
        roleKey: "",
        beginTime: "",
        finishTime: "",
      },
      createTime: [],
      input: "",
      options: [
        {
          value: "2",
          label: "所有",
        },
        {
          value: "0",
          label: "正常",
        },
        {
          value: "1",
          label: "停用",
        },
      ],
      value: "2",
      tableHeader: [
        {
          title: "角色编号",
          prop: "roleId",
          width: "80",
          align: "center",
          visible: true,
          sortble: false,
        },
        {
          title: "角色名称",
          prop: "roleName",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "权限字符",
          prop: "roleKey",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        // {
        //   title: "显示顺序",
        //   prop: "orderByColumn",
        //   width: "100",
        //   align: "center",
        //   visible: true,
        //   sortble: true,
        // },
        {
          title: "角色状态",
          prop: "status",
          width: "150",
          align: "center",
          visible: true,
          sortble: true,
        },
        {
          title: "创建时间",
          prop: "createTime",
          width: "200",
          align: "center",
          visible: true,
          sortble: true,
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      btnDisabledSingle: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      dialogAssignVisible: false,
      rowData: {},
      tableHeight: 550,
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },

  mounted() {
    this.calculateTableHeight();
    this.initTable();
  },
  methods: {
    initTable() {
      this.form.status = this.value == "2" ? "" : this.value;
      let data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        roleName: this.input,
        roleKey: this.form.roleKey,
        status: this.form.status,
        "params[beginTime]": this.form.beginTime,
        "params[endTime]": this.form.finishTime,
      };
      roleList(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.rows;
          this.total = res.total;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      if (this.multipleSelection.length == 1) {
        this.btnDisabledSingle = false;
      } else {
        this.btnDisabledSingle = true;
      }
    },
    handleClick(row, field) {
      switch (field) {
        case "add":
          this.field = "添加角色";
          this.dialogRoleVisible = true;
          this.rowData = {};
          break;
        case "edit":
          this.field = "修改角色";
          this.dialogRoleVisible = true;
          this.rowData = this.multipleSelection[0];
          break;
        case "assign":
          this.field = "分配用户";
          this.rowData = row;
          this.dialogAssignVisible = true;
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个角色吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let data = {
              ids: this.multipleSelection.map((item) => item.roleId),
            };
            roleRemove(data).then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.initTable();
              } else {
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          });
          break;
        case "export":
          let data = {
            roleName: this.input,
            roleKey: this.form.roleKey,
            status: this.form.status,
            "params[beginTime]": this.form.beginTime,
            "params[endTime]": this.form.finishTime,
          };
          roleExport(data).then((res) => {
            if (res.code == 0) {
              window.open(res.data.downLoadUrl, "_self");
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    handleSelectTime(val) {
      if (val && val.length) {
        this.form.beginTime = val[0];
        this.form.finishTime = val[1];
      }
    },
    resetForm(formName) {
      this.form = {
        // loginName: "",
        // ipaddr: "",
        roleKey: "",
        status: "",
        beginTime: "",
        finishTime: "",
      };
      this.value = "";
      this.createTime = [];
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
